package cn.com.kh;

import cn.com.elite.EliteBean;
import cn.com.elite.Util;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * @projectName: ngsapitask-sw
 * @package: cn.com.kh
 * @className: httpFileDownUtils
 * @author: LiJT
 * @description: 通用HTTP文件下载工具类
 * @date: 2023-03-17 14:26
 * @version: 1.0
 */
public class FileHttpUtils {
    private static final Log log = LogFactory.getLog(FileHttpUtils.class);
    private static long startTime = System.currentTimeMillis();

    // 文件下载方法
    public static String downFile(String url, Map<String, String> headers, String encode, String savePath, String saveName) {

        log.debug("httpFileDownUtils URL:" + url + " savePath:" + savePath);

        encode = KHUtil.isNull(encode) ? "UTF-8" : encode;

        CloseableHttpResponse httpResponse = null;
        CloseableHttpClient closeableHttpClient = null;

        FileOutputStream fs = null;
        InputStream inputStream = null;
        String saveFile = "";
        String filename = "";
        int bytesum = 0;
        int byteread = 0;

        try {
            // 建立连接对象
            closeableHttpClient = HttpClientBuilder.create().build();
            HttpGet httpGet = new HttpGet(url);

            // 设置请求头
            if (headers != null && headers.size() > 0) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    httpGet.setHeader(entry.getKey(), entry.getValue());
                }
            }

            // 调用URL获取文件
            httpResponse = closeableHttpClient.execute(httpGet);

            // 获取文件名&文件路径
            try {
                if (KHUtil.isNull(saveName)) {
                    filename = URLDecoder.decode(httpResponse.getHeaders("Content-Disposition")[0].getValue().substring(21), "UTF-8").replace("\"", "");
                    log.debug("通过Headers获取的文件名:" + filename);

                } else {
                    filename = saveName;
                    log.debug("1-使用指定的文件名:" + filename);
                }

            } catch (Exception e) {
                if (KHUtil.isNull(saveName)) {
                    filename = url.substring((url.lastIndexOf('/') + 1));
                    log.debug("通过URL链接获取的文件名:" + filename);
                } else {
                    filename = saveName;
                    log.debug("2-使用指定的文件名:" + filename);
                }

            } finally {
                // 获取当前时间
                SimpleDateFormat sm = new SimpleDateFormat("yyyyMMddHHmmss");
                String nowDate = sm.format(new Date());

                filename = KHUtil.isNull(filename) ? nowDate + "-" + KHUtil.getRandomString(6).toUpperCase() + ".jpg" : nowDate + "-" + KHUtil.getRandomString(6).toUpperCase() + "-" + filename;
                log.debug("获取的文件名检查保护:" + filename);
                saveFile = savePath + "/" + filename;
                log.debug("下载文件完整存储路径:" + saveFile);

            }

            // 获取下载文件流
            inputStream = httpResponse.getEntity().getContent();

            // 读取文件
            fs = new FileOutputStream(saveFile);
            byte[] buffer = new byte[1204];

            while ((byteread = inputStream.read(buffer)) != -1) {
                bytesum += byteread;
                fs.write(buffer, 0, byteread);
            }

        } catch (Exception e) {
            log.error("下载文件异常-", e);
        } finally {
            try {
                //关闭连接、释放资源
                httpResponse.close();
            } catch (IOException e) {
                log.warn("httpResponse.close()异常" + e.getMessage());
            }
            try {
                //关闭连接、释放资源
                inputStream.close();
            } catch (IOException e) {
                log.warn("inputStream.close()异常" + e.getMessage());
            }
            try {
                //关闭连接、释放资源
                fs.close();
            } catch (IOException e) {
                log.warn("fs.close异常" + e.getMessage());
            }
            try {
                //关闭连接、释放资源
                closeableHttpClient.close();
            } catch (IOException e) {
                log.warn("closeableHttpClient.close()异常" + e.getMessage());
            }
        }

        log.debug("文件下载完成路径:" + saveFile + " 耗时(毫秒):" + (System.currentTimeMillis() - startTime));
        return saveFile;
    }

    // 文件上传NGS
    public static String uploadNGS(EliteBean eliteBean, String savePath, String srcFileName) throws Exception {

        String ngsFSToken = Util.getAuthToken(KHDBConfig.getAPIURL(eliteBean, "NGS-FS-authUrl"), "elite.ngs", "Letmein_0308");
        log.debug("获取NGS上传Token：" + ngsFSToken);

        File tempFile = new File(srcFileName.trim());
        String fileName = tempFile.getName();
        log.debug("上传NGS文件名：" + fileName);

        savePath = KHUtil.isNull(savePath) ? "/headimg" : savePath;
        log.debug("上传NGS文件路径：" + savePath);

        String uploadResult = Util.uploadFile(KHDBConfig.getAPIURL(eliteBean, "NGS-FS-upload_url"), srcFileName, savePath, KHUtil.getNameWithoutSuffix(fileName), "", ngsFSToken);
        log.debug("文件NGS上传结果：" + uploadResult);

        JSONObject resultJson = JSONObject.fromObject(uploadResult);

        String code = resultJson.getString("code");
        if (code.equals("1")) {
            return resultJson.getString("value");
        } else {
            return null;
        }
    }
}
